using System;
//using System.Data;
using System.Collections;
//using System.Configuration;

/// <summary>
/// A generic sorter, inheriting from IComparer, 
/// intended to allow for the sorting of
/// strongly-typed collections on any named public property
/// which implements IComparable
/// </summary>
//[Serializable]
public class Comparer : IComparer
{
    string m_SortPropertyName ;
    SortDirection m_SortDirection ;

    /// <summary>
    /// Initializes an instance of the <see cref="Collections.Comparer"/> class.
    /// </summary>
    /// <param name="sortPropertyName">Property Name to sort on.</param>
    public Comparer(string sortPropertyName)
    {
        this.m_SortPropertyName = sortPropertyName ;
        this.m_SortDirection = SortDirection.ASC ;
        // default to ascending order
    }
    /// <summary>
    /// Initializes an instance of the <see cref="Collections.Comparer"/> class.
    /// </summary>
    /// <param name="sortPropertyName">Property Name to sort on.</param>
    /// <param name="sortDirection">Direction to sort.</param>
    public Comparer(string sortPropertyName, SortDirection sortDirection)
    {
        this.m_SortPropertyName = sortPropertyName ;
        this.m_SortDirection = sortDirection ;
    }

    /// <summary>
    /// Compare two objects.
    /// </summary>
    /// <param name="x">First object to compare.</param>
    /// <param name="y">Second object to compare.</param>
    /// <returns></returns>
    public int Compare(object x, object y)
    {
        // Get the values of the relevant property on the
        //  x and y objects

        object valueOfX = x.GetType().GetProperty(m_SortPropertyName).GetValue(x, null) ;
        object valueOfY = y.GetType().GetProperty(m_SortPropertyName).GetValue(y, null) ;

        IComparable comp = valueOfY as IComparable ;

        // Flip the value from whatever it was to the opposite.
        return Flip(comp.CompareTo(valueOfX)) ;
    }

    private int Flip(int i)
    {

        return (i * (int)m_SortDirection) ;

    }
}

/// <summary>
/// Enumerator to indicate whether to sort in ascending or descending order
/// </summary>
public enum SortDirection
{
    /// <remarks />
    ASC = -1,
    /// <remarks />
    DESC = 1
}